﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Dapper;
using DotnetSpider.DataFlow;
using DotnetSpider.DataFlow.Parser;
using DotnetSpider.DataFlow.Storage;
using DotnetSpider.Http;
using DotnetSpider.RequestSupplier;
using DotnetSpider.Scheduler.Component;
using DotnetSpider.Selector;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;

using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using Serilog;
using static DotnetSpider.Lawyee.Src.LawSpider;
using StringContent = DotnetSpider.Http.StringContent;

namespace DotnetSpider.Lawyee.Src
{
	public class cprqDataParser : DataParser
	{


		/// <summary>
		/// 根据日期生成 leftDataItem  请求
		/// </summary>
		/// <param name="startDate">开始日期</param>
		/// <param name="totalDays">0代表当天</param>
		/// <returns></returns>
		public static Request ConditionRequst(string startDate, int totalDays = 0)
		{
			Request request = null;
			try
			{
				JObject propertyItem = new JObject();

				propertyItem.Add(new JProperty("key", "cprq"));

				DateTime dtStart = Convert.ToDateTime(startDate);

				DateTime dtEnd = new DateTime();

				dtEnd = dtStart.AddDays(totalDays);

				string dtEndStr = dtEnd.ToString("yyyy-MM-dd");

				propertyItem.Add(new JProperty("value", startDate + " TO " + dtEndStr));

				JArray condition = new JArray();

				condition.Add(propertyItem);

				string conditionText = JsonConvert.SerializeObject(condition);

				//url = "https://2020.ip138.com/";

				request = CreateDocDataItemRequest(conditionText, "cprqDataParser");

				request.SetProperty("conditionText", conditionText);

				request.SetProperty("start", startDate);

				request.SetProperty("totalDays", totalDays.ToString());

			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "cprqDataParser:ConditionRequst:");
			}

			return request;
		}



		public cprqDataParser()
		{
			AddRequiredValidatorEx("cprqDataParser");
		}

		protected override Task Parse(DataContext context)
		{
			try
			{
				//左边菜单json
				var result = CommonHelper.CommonParser(context);

				if (string.IsNullOrEmpty(result) || !result.StartsWith("{") || !result.EndsWith("}"))
				{
					CommonHelper.RetryRequest(context);
					return Task.CompletedTask;
				}
				else
				{
					JObject dataItemResult = JObject.Parse(result);
					FilterData(context, dataItemResult);
				}

			}
			catch (Exception ex)
			{
				CommonHelper.RetryRequest(context);
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "cprqDataParser:Parse:");
			}

			return Task.CompletedTask;

		}


		/// <summary>
		/// 左边菜单列表根据   start   totalDays   生成按每天的左边刷选菜单
		/// </summary>
		/// <param name="context"></param>
		/// <param name="dataItemResult"></param>
		protected static void FilterData(DataContext context, JObject dataItemResult)
		{
			try
			{
				Request request = null;
				//总数
				int count = 0;
				if (dataItemResult.Property("s42") != null && dataItemResult["s42"].GetType() == typeof(JArray))
				{
					JArray jobjTotal = (JArray)dataItemResult["s42"];

					if (jobjTotal.Count > 0)
					{
						foreach (JObject everyYearTotal in jobjTotal)
						{
							count += int.Parse(everyYearTotal["count"].ToString());
						}
					}
				}

				string pageId = context.Request.GetProperty("pageId");

				JArray condition = JArray.Parse(context.Request.GetProperty("conditionText"));

				Dictionary<string, string> properties = context.Request.Properties;

				//当天信息加入redis，如果已经满了，就不用查了
				if (properties.ContainsKey("start") && properties.ContainsKey("totalDays"))
				{
					string startDate = properties["start"];
					string totalDays = properties["totalDays"];
					if (!string.IsNullOrEmpty(totalDays) && int.Parse(totalDays) < 1)  //当天
					{
						bool checkStatus = true;

						if (StartRedisQueue)
						{
							lock (RedisLocker)
							{
								string statusText = RedisHelpers.HashGet(DayStatus, startDate);

								JObject jobj = null;

								if (!string.IsNullOrEmpty(statusText))
								{
									jobj = JObject.Parse(statusText);

									int total = int.Parse(jobj["count"].ToString());

									if (jobj.Property("current") != null)
									{
										//记录总籹和当前记录之比
										int current = int.Parse(jobj["current"].ToString());

										//if (current == total)
										//{
										//	checkStatus = false;
										//}
										
										if (total > 0 && Convert.ToDouble(current / total) > 0.99)
										{
											checkStatus = false;
										}

									}

								}
								else
								{

									jobj = new JObject();
									jobj.Add(new JProperty("count", count));
									jobj.Add(new JProperty("current", 0));
									RedisHelpers.HashSet(DayStatus, startDate, JsonConvert.SerializeObject(jobj));

									using (var conn = new SqlConnection(Options_.StorageConnectionString))
									{
										conn.Execute(
										$"update lawyee.dbo.dateOne  WITH (TABLOCKX) set totalcount = @totalcount where dateone = @dateone",new { totalcount = Convert.ToInt32(count), dateone = startDate });

									}

								}

							}

						}

						if (!checkStatus)
						{
							Log.Logger.Warning($"发现重复的查询日期{ startDate }");
							return;
						}

					}
				}


				if (count <= MaxRecord && count > 0)  //小于当前设定值, 无需进行过虑
				{
					//直接查询文书id
					ScrollPage(count, pageId, condition, context);

				}
				else
				{ //解析过虑条件

					int totalDays = int.Parse(context.Request.GetProperty("totalDays"));

					string start = context.Request.GetProperty("start");

					if (totalDays > 0)
					{

						//Dictionary<string, int> dateDict = SplitDate(start, totalDays);
						Dictionary<string, int> dateDict = CommonHelper.SplitDateForDay(start, totalDays);

						foreach (KeyValuePair<string, int> dateItem in dateDict)
						{
							request = ConditionRequst(dateItem.Key, dateItem.Value);
							context.AddFollowRequests(request);
						}


					}
					else  //1天之内还是大于recordmax
					{
					     s2DataParser.s2DataParserCreateSubRquest(context, dataItemResult, pageId, condition);

					}
				}

			}
			catch (Exception ex)
			{
				Log.Logger.Error(ex.Message + "!!!"+ ex.StackTrace + "cprqDataParser:FilterData:");
			}

		}
	}

	




































}
